// 路由配置：定义四个模块的页面路由
import { createRouter, createWebHistory } from 'vue-router'

const Products = () => import('../pages/Products.vue')
const Categories = () => import('../pages/Categories.vue')
const Login = () => import('../pages/Login.vue')
const Users = () => import('../pages/Users.vue')
const Orders = () => import('../pages/Orders.vue')
const Coupons = () => import('../pages/Coupons.vue')

const routes = [
  { path: '/', redirect: '/products' },
  { path: '/login', name: 'login', component: Login },
  { path: '/categories', name: 'categories', component: Categories },
  { path: '/products', name: 'products', component: Products },
  { path: '/users', name: 'users', component: Users },
  { path: '/orders', name: 'orders', component: Orders },
  { path: '/coupons', name: 'coupons', component: Coupons }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫：除 /login 外，均需已登录（localStorage 中存在 token）
router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next()
  const token = localStorage.getItem('token')
  if (!token) return next('/login')
  next()
})

export default router